/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.subscription;

import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.persistence.exception.DeleteException;
import com.blandware.atleap.service.exception.BeanNotFoundException;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.forum.ForumSubscriptionForm;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Deletes an email subscription to forum or topic.</p>
 * <p><a href="DeleteForumSubscriptionAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.2 $ $Date: 2008/04/29 17:51:51 $
 * @struts.action path="/forum/subscription/delete"
 * name="forumSubscriptionForm"
 * scope="request"
 * validate="false"
 * @struts.action-forward name="showForum"
 * path="/forum/forum/show.do"
 * redirect="true"
 * @struts.action-forward name="showTopic"
 * path="/forum/topic/show.do"
 * redirect="true"
 */
public final class DeleteForumSubscriptionAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) {

        ForumSubscriptionForm forumSubscriptionForm = (ForumSubscriptionForm) form;

        HttpSession session = request.getSession();

        Long topicId = null;
        Long forumId = null;
        Long id = null;
        String token = null;
        if (!GenericValidator.isBlankOrNull(forumSubscriptionForm.getId())) {
            try {
                id = Long.valueOf(forumSubscriptionForm.getId());
            } catch (NumberFormatException e) {
            }
        }
        if (!GenericValidator.isBlankOrNull(request.getParameter("forumId"))) {
            try {
                forumId = Long.valueOf(request.getParameter("forumId"));
            } catch (NumberFormatException e) {
            }
        } else if (session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY) != null) {
            forumId = (Long) session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY);
        }
        if (!GenericValidator.isBlankOrNull(request.getParameter("topicId"))) {
            try {
                topicId = Long.valueOf(request.getParameter("topicId"));
            } catch (NumberFormatException e) {
            }
        } else if (session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY) != null) {
            topicId = (Long) session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY);
        }
        token = request.getParameter("token");

        ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
        String remoteUser = request.getRemoteUser();
        boolean anonymous = remoteUser == null;

        try {
            if (anonymous) {
                // we must get subscription ID and token
                if (id == null) {
                    ActionMessages errors = new ActionMessages();
                    errors.add("cannotDeleteSubscription", new ActionMessage("forum.subscription.errors.noIdSpecified"));
                    saveErrors(request, errors);
                    return mapping.findForward("showForum");
                }
                if (token == null) {
                    ActionMessages errors = new ActionMessages();
                    errors.add("cannotDeleteSubscription", new ActionMessage("forum.subscription.errors.noTokenSpecified"));
                    saveErrors(request, errors);
                    return mapping.findForward("showForum");
                }
                forumManager.deleteSubscription(id, token);
            } else {
                // we must get forum or topic ID
                if (forumId == null && topicId == null) {
                    ActionMessages errors = new ActionMessages();
                    errors.add("noTopicOrForumSpecified", new ActionMessage("forum.subscription.errors.noTopicOrForumSpecified"));
                    saveErrors(request, errors);
                    return mapping.findForward("showForum");
                }
                forumManager.deleteSubscription(forumId, topicId, remoteUser);
            }
        } catch (BeanNotFoundException e) {
            ActionMessages errors = new ActionMessages();
            errors.add("subscriptionNotFound", new ActionMessage("forum.subscription.errors.notFound"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        } catch (DeleteException e) {
            ActionMessages errors = new ActionMessages();
            errors.add("cannotDelete", new ActionMessage("forum.subscription.errors.cannotDelete"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        ActionMessages messages = new ActionMessages();
        messages.add("success", new ActionMessage("forum.subscription.messages.successfullyDeleted"));
        saveMessages(request, messages);
        return mapping.findForward("showForum");
	}
}
